package com.xz.usercenter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.usercenter.common.ErrorCode;
import com.xz.usercenter.exception.BusinessException;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.service.UserService;
import com.xz.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xz.usercenter.constant.UserConstant.USER_LOGIN_STATUS;

/**
* @author 徐洲
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-04-21 15:24:31
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /**
     * 盐值 混淆密码
     */
    private static final String SIGN = "xz";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String verificationCode) {
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度应大于等于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度应大于等于8位");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码输入不一致");
        }
        if (verificationCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "校验码长度应小于5位");
        }
        // 用户账号不能包含特殊字符
        String regEx = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (!matcher.matches()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不能包含特殊字符");
        }
        // 用户账号不允许重复
        Long count = lambdaQuery().eq(User::getUserAccount, userAccount).count();
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号重复");
        }

        // 校验码不允许重复
        count = lambdaQuery().eq(User::getVerificationCode, verificationCode).count();
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "校验码重复");
        }

        // 插入用户
        // 1.用户密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SIGN + userPassword).getBytes());
        // 2.保存数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setVerificationCode(verificationCode);
        boolean saveResult = this.save(user);
        if (!saveResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册失败");
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度应大于等于4位");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度应大于等于8位");
        }
        // 用户账号不能包含特殊字符
        String regEx = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (!matcher.matches()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不能包含特殊字符");
        }
        // 用户密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SIGN + userPassword).getBytes());
        // 2.查询用户是否存在
        User user = lambdaQuery().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, encryptPassword).one();
        if (user == null){
//            log.info("用户账号或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号或密码错误");
        }
        // 3.脱敏 防止把数据库的数据泄露给前端
        User safetyUser = getSafetyUser(user);
        // 4.记录用户的登录状态
        request.getSession().setAttribute(USER_LOGIN_STATUS, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏 防止把数据库的数据泄露给前端
     * @param originalUser 原始数据
     * @return
     */
    @Override
    public User getSafetyUser(User originalUser){
        if (originalUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(originalUser.getId());
        safetyUser.setUserName(originalUser.getUserName());
        safetyUser.setUserAccount(originalUser.getUserAccount());
        safetyUser.setAvatarUrl(originalUser.getAvatarUrl());
        safetyUser.setUserRole(originalUser.getUserRole());
        safetyUser.setGender(originalUser.getGender());
        safetyUser.setPhone(originalUser.getPhone());
        safetyUser.setEmail(originalUser.getEmail());
        safetyUser.setVerificationCode(originalUser.getVerificationCode());
        safetyUser.setUserStatus(originalUser.getUserStatus());
        safetyUser.setCreateTime(originalUser.getCreateTime());
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除用户登录态
        request.getSession().removeAttribute(USER_LOGIN_STATUS);
        return 1;
    }
}




